package com.easyexcle.demo.easyExcel.style;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PropertyPlaceholderHelper;

import java.util.List;
import java.util.Properties;

/**
 * @Author: lkz
 * @Title: EasyExcelTitleHandler
 * @Description: 动态表头字段匹配
 * @Date: 2023/8/2 11:10
 */

public class EasyExcelTitleHandler  implements CellWriteHandler {

    private String title;
    private String t2;



    public EasyExcelTitleHandler(String title,String t2) {
        this.title = title;
        this.t2 = t2;
    }

    PropertyPlaceholderHelper placeholderHelper = new PropertyPlaceholderHelper("${", "}");
    PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}");


    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
        // 动态设置表头字段
        if(isHead){
            if (!ObjectUtils.isEmpty(head)) {
                List<String> headNameList = head.getHeadNameList();
                if (CollectionUtils.isNotEmpty(headNameList)) {
                    Properties properties = new Properties();
                    properties.setProperty("title", title);
                    Properties properties1 = new Properties();
                    properties1.setProperty("year", t2);
                    for (int i = 0 ; i < headNameList.size() ; i++){
                        // 循环遍历替换
                        headNameList.set(i, placeholderHelper.replacePlaceholders(headNameList.get(i), properties));
                        headNameList.set(i, helper.replacePlaceholders(headNameList.get(i), properties1));
                    }
                }
            }
        }

    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {

    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {

    }

}
